<template>
  <div id="login">
    <van-nav-bar
      title="登录"
      left-arrow
      class="page-nav-bar"
      @click-left="$router.back()"
    />
    <van-form @submit="onSubmit" ref="loginRef">
      <!-- 输入手机号，调起手机号键盘 -->
      <van-field
        v-model="user.mobile"
        name="mobile"
        type="number"
        placeholder="请输入手机号"
        clearable
        maxlength="11"
        :rules="userFormRules.mobile"
      >
        <!-- 插槽添加自定义图标 -->
        <i slot="left-icon" class="iconfont iconshouji"></i>
      </van-field>
      <!-- 短信验证码 -->
      <van-field
        v-model="user.code"
        name="code"
        center
        clearable
        placeholder="请输入验证码"
        maxlength="6"
        type="number"
        :rules="userFormRules.code"
      >
        <i slot="left-icon" class="iconfont iconyanzhengma"></i>
        <template #button>
          <van-button
            size="small"
            round
            class="verfiBtn"
            @click="getCode"
            v-if="!timeOutVisable"
            >获取验证码</van-button
          >
          <!-- 倒计时 -->
          <!-- <div v-if="timeOutVisable">{{ timeOut }}</div> -->
          <van-count-down
            :time="1000 * 60"
            format="ss s"
            @finish="timeOutVisable = false"
            v-else
          ></van-count-down>
        </template>
      </van-field>
      <div class="loginBtn_box">
        <van-button block type="default" class="loginBtn">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
/**
 * try {
 *   tryCode - 尝试执行代码块
 *}
 *catch(err) {
 *    catchCode - 捕获错误的代码块
 *}
 *finally {
 *    finallyCode - 无论 try / catch 结果如何都会执行的代码块
 *}
 */
// 按需引入Api
import { login, getSms } from '@/api/user'
export default {
  name: 'Login',
  data() {
    return {
      user: {
        mobile: '13911111111',
        code: '246810'
      },
      userFormRules: {
        mobile: [
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3|5|7|8]\d{9}$/, message: '手机号格式错误' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' }
        ]
      },
      // timeOut: 60,
      timeOutVisable: false
    }
  },
  methods: {
    // 表单提交
    async onSubmit(values) {
      // console.log('submit', values)
      // 验证表单的数据
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续展示,直到成功,另一个toast被调用
      })
      try {
        const {
          data: { data }
        } = await login(this.user)
        // console.log('成功', res)
        this.$toast.success('登录成功')
        // 登录成功后将token存储起来
        // console.log(data)
        this.$store.commit('setUserToken', data)

        // 跳转页面
        this.$router.push('/layout')
      } catch (error) {
        if (error.response.status === 400) {
          // return console.log('登录失败')
          return this.$toast.fail('登录失败,检查用户名或密码后再登录')
        }
        // console.log('服务器异常,请稍后再登录')
        return this.$toast.fail('服务器异常,请稍后再登录')
      }
    },

    // 点击获取验证码
    async getCode() {
      // 单独验证手机号码 返回promise
      try {
        await this.$refs.loginRef.validate('mobile')
      } catch (error) {
        return this.$toast.fail('验证失败', error)
      }
      // TODO: 手机号验证成功后显示倒计时
      this.timeOutVisable = true
      // 启用定时器
      // const timeID = setInterval(() => {
      //   if (this.timeOut < 51) {
      //     this.timeOut = 60
      //     this.timeOutVisable = false
      //     clearInterval(timeID)
      //     return this.$toast.fail('获取验证码失败')
      //   }
      //   this.timeOut--
      // }, 1000)

      // 发送请求拿到验证码
      try {
        await getSms(this.user.mobile)
        // console.log(res)
        this.$toast.success('获取验证码成功')
      } catch (error) {
        if (error.response.status === 429) {
          return this.$toast.fail('请勿多次请求')
        }
        return this.$toast.fail('获取验证码失败')
      }
    }
  },
  created() {}
}
</script>

<style lang="less" scoped>
#login {
  .iconfont {
    font-size: 37px;
  }
}
.verfiBtn {
  width: 158px;
  height: 55px;
  font-size: 22px;
  background-color: #ededed;
  color: #666;
}
.loginBtn_box {
  padding: 53px 33px;
}
.loginBtn {
  background-color: #6db4fb;
  border: none;
  color: #fff;
  font-size: 30px;
}
</style>
